package com.gang.controller;


import com.gang.pojo.CommonResult;
import com.gang.pojo.Datas;
import com.gang.pojo.Vp;
import com.gang.service.BlockService;
import com.gang.utils.PDF;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

@Controller
@RequestMapping("/block")
@Api(tags = "区块链服务")
public class BlockController {

    @Autowired
    BlockService blockService;

    @RequestMapping("/getkey")
    @ResponseBody
    public int getkey( HttpServletResponse response) throws UnsupportedEncodingException {
        UUID uuid = blockService.getPubPriKey();
        String fileName = uuid.toString()+".txt"; //下载的文件名

        // 如果文件名不为空，则进行下载
        if (fileName != null) {
            //设置文件路径
            String realPath = "H:/";
            File file = new File(realPath, fileName);

            // 如果文件名存在，则进行下载
            if (file.exists()) {

                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setHeader("Content-Length",""+file.length());
                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return 1;
    }

    @RequestMapping("/adddid/{pub}/{pri}")
    @ResponseBody
    public CommonResult addDid(@PathVariable("pub") String pub,@PathVariable("pri") String pri) throws Exception {
        String did = blockService.getDidAndToChain( pub, pri);
        if(did.equals("")){
            return new CommonResult(400,"失败",-1);
        }else
            return new CommonResult(200,"成功",did);
    }

    @RequestMapping("/getVC/{did}/{pub}/{data}/{pri}")
    @ResponseBody
    @ApiOperation("获取凭证")
    public String getVC(HttpServletResponse response,@PathVariable("did") String did,@PathVariable("pub") String pub,@PathVariable("data") String data,@PathVariable("pri") String pri) throws UnsupportedEncodingException {

        UUID uuid = blockService.getVC(did, pub, data, pri);
        UUID getpdf = PDF.getpdf(uuid);
        String fileName = getpdf+".pdf"; //下载的文件名

        // 如果文件名不为空，则进行下载
        if (fileName != null) {
            //设置文件路径
            String realPath = "H:/";
            File file = new File(realPath, fileName);

            // 如果文件名存在，则进行下载
            if (file.exists()) {

                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setHeader("Content-Length",""+file.length());
                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    @RequestMapping("/getvp/{did}/{pub}/{data}/{root}/{sign}/{pri}")
    @ResponseBody
    @ApiOperation("获取Vp")
    public CommonResult getVp(HttpServletResponse response,@PathVariable("did") String did,@PathVariable("pub")String pub,@PathVariable("data")String data,@PathVariable("root")String root,@PathVariable("sign")String sign, @PathVariable("pri")String pri) throws Exception {
        UUID uuid = blockService.getVP(did, pub, data, root, sign, pri);
        UUID getpdf = PDF.getpdf(uuid);
        String fileName = getpdf+".pdf"; //下载的文件名

        // 如果文件名不为空，则进行下载
        if (fileName != null) {
            //设置文件路径
            String realPath = "H:/";
            File file = new File(realPath, fileName);

            // 如果文件名存在，则进行下载
            if (file.exists()) {

                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setHeader("Content-Length",""+file.length());
                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return new CommonResult(200,"1",1);
    }

    @RequestMapping("/verifyroot/{data}/{index}")
    @ResponseBody
    @ApiOperation("验证root")
    public CommonResult verifyRoot(@PathVariable("data") String data,@PathVariable("index") int index) throws Exception {
        String s = blockService.verifyRoot(data,index);
            return new CommonResult(200, "hash结果", s);
    }

    @RequestMapping("/verifysign/{index}/{data}/{sign}/{pub}")
    @ResponseBody
    @ApiOperation("验证签名")//int index,String data,String sign, String pub
    public CommonResult verifysign(@PathVariable("index")int index,@PathVariable("data")String data,@PathVariable("sign") String sign,@PathVariable("pub") String pub) throws Exception {

        Boolean aBoolean = blockService.verifySign(index,data, sign, pub);
        if (aBoolean)
            return new CommonResult(200,"验证通过",aBoolean);
        else
            return new CommonResult(400,"验证失败",aBoolean);
    }

    @RequestMapping("/verifydid/{vphash}/{time}")
    @ResponseBody
    @ApiOperation("验证did")
    public CommonResult verifydid(@PathVariable("vphash")String vphash,@PathVariable("time")String time) throws Exception {
        String s = blockService.verifyDid(vphash, time);
            return new CommonResult(200,"did",s);
    }

    @RequestMapping("/getdid/{pri}/{vphash}")
    @ResponseBody
    @ApiOperation("获取did")
    public CommonResult getdid(@PathVariable("pri")String pri,@PathVariable("vphash")String vphash) throws Exception {
        String s = blockService.getDid(pri, vphash);
        return new CommonResult(200,"did",s);
    }

    @RequestMapping("/deploy/{pri}")
    @ResponseBody
    @ApiOperation("部署合约")
    public CommonResult deployContract(@PathVariable("pri")String pri) throws Exception {
        String s = blockService.deployContract(pri);
        return new CommonResult(200,"address",s);
    }

    @RequestMapping("/nft/{tokenURI}/{pri}")
    public CommonResult setnft(@PathVariable("tokenURI")String tokenURI,@PathVariable("pri")String pri,String addr){
        Datas datas = blockService.setnft(tokenURI, pri, addr);
        return new CommonResult(200,"datas",datas);
    }
}
